//+------------------------------------------------------------------+
//|                                              MarketState.mqh |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024"
#property link      ""
#property version   "1.00"
#property strict

// 市场状态枚举
enum ENUM_MARKET_STATE {
    MARKET_TRENDING_UP,     // 上升趋势市场
    MARKET_TRENDING_DOWN,   // 下降趋势市场
    MARKET_RANGING,         // 区间震荡市场
    MARKET_VOLATILE,        // 高波动市场
    MARKET_CALM             // 低波动市场
};

// 市场状态结构
struct MarketState {
    ENUM_MARKET_STATE type;     // 市场状态类型
    double volatility;          // 波动率
    double trendStrength;       // 趋势强度
    double rangeSize;           // 区间大小
    datetime startTime;         // 开始时间
    datetime endTime;           // 结束时间
    bool isActive;              // 是否活跃
};

// 市场状态分析类
class CMarketStateAnalysis {
private:
    MarketState m_states[];     // 市场状态数组
    int m_stateCount;           // 状态计数
    int m_currentState;         // 当前状态索引
    
    // 分析参数
    int m_volatilityPeriod;     // 波动率计算周期
    int m_trendPeriod;          // 趋势计算周期
    double m_volatilityThreshold; // 波动率阈值
    double m_trendThreshold;    // 趋势阈值
    double m_rangeThreshold;    // 区间阈值
    
    // 指标句柄
    int m_atrHandle;            // ATR句柄
    int m_maHandle;             // MA句柄
    int m_bbHandle;             // 布林带句柄
    
public:
    // 构造函数
    CMarketStateAnalysis() {
        m_stateCount = 0;
        m_currentState = -1;
        m_volatilityPeriod = 14;        // 默认波动率周期
        m_trendPeriod = 20;             // 默认趋势周期
        m_volatilityThreshold = 0.02;   // 默认波动率阈值
        m_trendThreshold = 0.6;         // 默认趋势阈值
        m_rangeThreshold = 0.01;        // 默认区间阈值
    }
    
    // 初始化
    bool Initialize(int volatilityPeriod = 14, int trendPeriod = 20,
                   double volatilityThreshold = 0.02, double trendThreshold = 0.6,
                   double rangeThreshold = 0.01) {
        m_volatilityPeriod = volatilityPeriod;
        m_trendPeriod = trendPeriod;
        m_volatilityThreshold = volatilityThreshold;
        m_trendThreshold = trendThreshold;
        m_rangeThreshold = rangeThreshold;
        
        // 创建指标句柄
        m_atrHandle = iATR(Symbol(), PERIOD_CURRENT, m_volatilityPeriod);
        if(m_atrHandle == INVALID_HANDLE) return false;
        
        m_maHandle = iMA(Symbol(), PERIOD_CURRENT, m_trendPeriod, 0, MODE_SMA, PRICE_CLOSE);
        if(m_maHandle == INVALID_HANDLE) return false;
        
        m_bbHandle = iBands(Symbol(), PERIOD_CURRENT, m_trendPeriod, 0, 2.0, PRICE_CLOSE);
        if(m_bbHandle == INVALID_HANDLE) return false;
        
        return true;
    }
    
    // 分析市场状态
    bool AnalyzeMarketState(const double &high[], const double &low[], const double &close[], int count) {
        if(count < m_trendPeriod) return false;
        
        // 重置状态数组
        ArrayResize(m_states, 0);
        m_stateCount = 0;
        m_currentState = -1;
        
        // 获取指标数据
        double atrBuffer[];
        double maBuffer[];
        double upperBand[];
        double lowerBand[];
        
        ArraySetAsSeries(atrBuffer, true);
        ArraySetAsSeries(maBuffer, true);
        ArraySetAsSeries(upperBand, true);
        ArraySetAsSeries(lowerBand, true);
        
        if(CopyBuffer(m_atrHandle, 0, 0, count, atrBuffer) != count) return false;
        if(CopyBuffer(m_maHandle, 0, 0, count, maBuffer) != count) return false;
        if(CopyBuffer(m_bbHandle, 1, 0, count, upperBand) != count) return false;
        if(CopyBuffer(m_bbHandle, 2, 0, count, lowerBand) != count) return false;
        
        // 分析市场状态
        for(int idx = m_trendPeriod; idx < count; idx++) {
            if(IsStateChange(atrBuffer, maBuffer, upperBand, lowerBand, close, idx)) {
                AddMarketState(atrBuffer, maBuffer, upperBand, lowerBand, close, idx);
            }
        }
        
        return m_stateCount > 0;
    }
    
    // 检查状态是否改变
    bool IsStateChange(const double &atrBuffer[], const double &maBuffer[],
                      const double &upperBand[], const double &lowerBand[],
                      const double &close[], int barIndex) {
        // 计算当前波动率
        double currentVolatility = atrBuffer[barIndex] / close[barIndex];
        double prevVolatility = atrBuffer[barIndex + 1] / close[barIndex + 1];
        
        // 计算趋势强度
        double trendStrength = MathAbs(maBuffer[barIndex] - maBuffer[barIndex + 1]) / atrBuffer[barIndex];
        
        // 计算区间大小
        double rangeSize = (upperBand[barIndex] - lowerBand[barIndex]) / close[barIndex];
        
        // 检查状态变化条件
        return (MathAbs(currentVolatility - prevVolatility) > m_volatilityThreshold) ||
               (MathAbs(trendStrength) > m_trendThreshold) ||
               (MathAbs(rangeSize - m_rangeThreshold) > m_rangeThreshold);
    }
    
    // 添加市场状态
    void AddMarketState(const double &atrBuffer[], const double &maBuffer[],
                       const double &upperBand[], const double &lowerBand[],
                       const double &close[], int barIndex) {
        MarketState state;
        state.startTime = TimeCurrent();
        state.isActive = true;
        
        // 计算状态特征
        state.volatility = atrBuffer[barIndex] / close[barIndex];
        state.trendStrength = (maBuffer[barIndex] - maBuffer[barIndex + 1]) / atrBuffer[barIndex];
        state.rangeSize = (upperBand[barIndex] - lowerBand[barIndex]) / close[barIndex];
        
        // 确定状态类型
        if(state.volatility > m_volatilityThreshold * 2) {
            state.type = MARKET_VOLATILE;
        } else if(state.volatility < m_volatilityThreshold * 0.5) {
            state.type = MARKET_CALM;
        } else if(MathAbs(state.trendStrength) > m_trendThreshold) {
            state.type = (state.trendStrength > 0) ? MARKET_TRENDING_UP : MARKET_TRENDING_DOWN;
        } else {
            state.type = MARKET_RANGING;
        }
        
        // 添加到状态数组
        ArrayResize(m_states, m_stateCount + 1);
        m_states[m_stateCount++] = state;
        m_currentState = m_stateCount - 1;
    }
    
    // 更新当前状态
    bool UpdateCurrentState(const double &atrBuffer[], const double &maBuffer[],
                          const double &upperBand[], const double &lowerBand[],
                          const double &close[], int barIndex) {
        if(m_currentState < 0) return false;
        
        MarketState &currentState = m_states[m_currentState];
        
        // 更新状态结束时间
        currentState.endTime = TimeCurrent();
        
        // 检查状态是否结束
        if(IsStateChange(atrBuffer, maBuffer, upperBand, lowerBand, close, barIndex)) {
            currentState.isActive = false;
            return true;
        }
        
        return false;
    }
    
    // 获取当前状态
    bool GetCurrentState(MarketState &state) {
        if(m_currentState < 0 || m_currentState >= m_stateCount) return false;
        
        state = m_states[m_currentState];
        return true;
    }
    
    // 获取状态数量
    int GetStateCount() {
        return m_stateCount;
    }
    
    // 获取指定索引的状态
    bool GetState(int index, MarketState &state) {
        if(index < 0 || index >= m_stateCount) return false;
        
        state = m_states[index];
        return true;
    }
    
    // 预测状态延续性
    bool PredictStateContinuation(MarketState &predictedState) {
        if(m_currentState < 0) return false;
        
        MarketState currentState = m_states[m_currentState];
        
        // 预测状态延续
        predictedState = currentState;
        predictedState.startTime = currentState.endTime;
        
        // 根据当前状态特征预测
        predictedState.volatility *= 0.9;    // 假设波动率会略微降低
        predictedState.trendStrength *= 0.8;  // 假设趋势强度会略微减弱
        
        predictedState.isActive = true;
        return true;
    }
    
    // 验证状态有效性
    bool ValidateState() {
        if(m_currentState < 0) return false;
        
        MarketState currentState = m_states[m_currentState];
        
        // 检查状态是否有效
        return currentState.isActive &&
               (TimeCurrent() - currentState.startTime) < PeriodSeconds(PERIOD_D1); // 状态持续时间不超过1天
    }
    
    // 清理过期状态
    void CleanupOldStates(int maxAge) {
        for(int idx = m_stateCount - 1; idx >= 0; idx--) {
            if(!m_states[idx].isActive && 
               (TimeCurrent() - m_states[idx].endTime) > maxAge) {
                // 移除过期状态
                for(int jdx = idx; jdx < m_stateCount - 1; jdx++) {
                    m_states[jdx] = m_states[jdx + 1];
                }
                m_stateCount--;
            }
        }
    }
    
private:
    // 获取ATR值
    double GetATRValue(int shift) {
        double atrBuffer[];
        ArraySetAsSeries(atrBuffer, true);
        
        bool atrCopySuccess = (CopyBuffer(m_atrHandle, 0, shift, 1, atrBuffer) == 1);
        if(!atrCopySuccess) {
            return 0.0;
        }
        
        return atrBuffer[0];
    }
    
    // 获取MA值
    double GetMAValue(int shift) {
        double maBuffer[];
        ArraySetAsSeries(maBuffer, true);
        
        bool maCopySuccess = (CopyBuffer(m_maHandle, 0, shift, 1, maBuffer) == 1);
        if(!maCopySuccess) {
            return 0.0;
        }
        
        return maBuffer[0];
    }
    
    // 获取布林带值
    bool GetBBValues(int shift, double &upper, double &lower) {
        double upperBuffer[];
        double lowerBuffer[];
        ArraySetAsSeries(upperBuffer, true);
        ArraySetAsSeries(lowerBuffer, true);
        
        bool bbCopySuccess = (CopyBuffer(m_bbHandle, 1, shift, 1, upperBuffer) == 1) &&
                           (CopyBuffer(m_bbHandle, 2, shift, 1, lowerBuffer) == 1);
        if(!bbCopySuccess) {
            return false;
        }
        
        upper = upperBuffer[0];
        lower = lowerBuffer[0];
        return true;
    }
}; 